package com.cloud.spring.optional;

import com.cloud.spring.demo.entity.Address;
import com.cloud.spring.demo.entity.User;
import lombok.extern.log4j.Log4j2;

import java.util.Optional;

@Log4j2
public class OptionalDemo {
    public static void main(String[] args) {
        log.info("结束");
        //get()方法返回Optional<T>中的T对象
        Optional<User> optionalUser = getUser();
        //isPresent()方法用于判断Optional中的值是否存在
        if(optionalUser.isPresent()){
            User user = optionalUser.get();
            log.info(user);
            //map()方法从一个Option<User>中提取出Option<String>
            Optional<String>name=optionalUser.map(User::getName);
            log.info(name.get());
            Optional<Address> addressOptional=getAddress();
            log.info(addressOptional.map(Address::getUser).map(User::getName).orElse("jany"));
        }
        Optional<User> optionalUser1 = Optional.empty();
        log.info(optionalUser1);
    }

    public static Optional<User> getNullUser() {
        log.info("开始");
        //Optional.of()用于创建一个带参数的Optional对象，如果传入的值为null，会报空指针异常
       // return Optional.of(null);
        //Optional.ofNullable()允许传入的参数为null，需要调用端通过isPresent方法判断是否为Null
        return Optional.ofNullable(null);
    }
    public static Optional<User> getUser() {
        log.info("开始");
        //Optional.of()用于创建一个带参数的Optional对象，如果传入的值为null，会报空指针异常
        User user=new User();
        user.setName("tom");
         return Optional.of(user);
    }
    public static Optional<Address> getAddress(){
        Address address=new Address();
        address.setAddress("YanTai");
        User user=new User();
        user.setName("jams");
        address.setUser(user);
        return Optional.of(address);
    }
}
